package services

import (
	"goravel/app/models"
	"strings"

	"github.com/goravel/framework/facades"
)

type PermissionService struct {
}

func NewPermissionService() *PermissionService {
	return &PermissionService{}
}

// CheckUserPermission 检查用户是否有指定权限
func (s *PermissionService) CheckUserPermission(userID uint, path string, method string) (bool, error) {
	// 如果是超级用户，直接返回true
	var user models.User
	if err := facades.Orm().Query().Find(&user, userID); err != nil {
		return false, err
	}

	if user.IsRoot == 1 {
		return true, nil
	}

	// 构建权限键
	permKey := s.buildPermissionKey(path, method)
	permKey = strings.TrimLeft(permKey, "/")

	// 查询用户权限
	var count int64
	err := facades.Orm().Query().
		Table("users").
		Join("INNER JOIN user_roles ON users.id = user_roles.user_id").
		Join("INNER JOIN role_permissions ON user_roles.role_id = role_permissions.role_id").
		Join("INNER JOIN permissions ON role_permissions.permission_id = permissions.id").
		Where("users.id", userID).
		Where("permissions.perm_key", permKey).
		Count(&count)

	if err != nil {
		return false, err
	}

	return count > 0, nil
}

// GetUserPermissions 获取用户所有权限
func (s *PermissionService) GetUserPermissions(userID uint) ([]models.Permission, error) {
	var permissions []models.Permission

	// 如果是超级用户，返回所有权限
	var user models.User
	if err := facades.Orm().Query().Find(&user, userID); err != nil {
		return nil, err
	}

	if user.IsRoot == 1 {
		if err := facades.Orm().Query().Find(&permissions); err != nil {
			return nil, err
		}
		return permissions, nil
	}

	// 查询用户权限
	err := facades.Orm().Query().
		Table("permissions").
		Join("role_permissions", "permissions.id", "=", "role_permissions.permission_id").
		Join("user_roles", "role_permissions.role_id", "=", "user_roles.role_id").
		Where("user_roles.user_id", userID).
		Find(&permissions)

	return permissions, err
}

// GetUserRoles 获取用户角色
func (s *PermissionService) GetUserRoles(userID uint) ([]models.Role, error) {
	var roles []models.Role

	err := facades.Orm().Query().
		Table("roles").
		Join("user_roles", "roles.id", "=", "user_roles.role_id").
		Where("user_roles.user_id", userID).
		Find(&roles)

	return roles, err
}

// buildPermissionKey 构建权限键
func (s *PermissionService) buildPermissionKey(path string, method string) string {
	// 如果是GET请求且路径不包含参数，直接返回路径
	if method == "GET" && !strings.Contains(path, "{") {
		return path
	}

	// 对于其他请求方法，添加方法后缀

	return path + ":" + method
}

// MatchRoute 匹配路由
func (s *PermissionService) MatchRoute(permissionRoute string, requestPath string) bool {
	// 如果权限路由是通配符，直接匹配
	if permissionRoute == "*" {
		return true
	}

	// 如果任一路径为空，直接返回 false
	if permissionRoute == "" || requestPath == "" {
		return false
	}

	// 将权限路由和请求路径拆分为片段
	permissionParts := strings.Split(permissionRoute, "/")
	requestParts := strings.Split(requestPath, "/")

	// 如果片段数量不匹配，直接返回 false
	if len(permissionParts) != len(requestParts) {
		return false
	}

	// 逐个片段匹配
	for i := 0; i < len(permissionParts); i++ {
		if permissionParts[i] != requestParts[i] && !strings.HasPrefix(permissionParts[i], "{") {
			return false
		}
	}

	return true
}
